// @ts-nocheck
import {ref, h , computed, reactive, onBeforeMount} from "vue";
import {ElMessage, ElNotification} from "element-plus";
import  {axios_request, } from "@/api/milliaAxios";
import {useUserStore} from "@/stores/userStore";
import {sleep} from "@/static/Login_Register/register";


// ==============================================================================
const userStore = useUserStore();
export const userData = ref(userStore.userData).value;

export const useUserStoreInfo = () => {

    // 定义一个函数来调用 fetchUserInfo
    const fetchUserInformation = async () => {
        const keys = ['gender', 'last_login', 'create_time', 'username', 'signature'];
        if (userStore.UID) {
            const newUserData = await userStore.fetchUserInfo(keys, userStore.UID);
            userStore.updateUserData(newUserData);
        }
    };

    // 在组件挂载之前获取用户信息
    onBeforeMount(async () => {
        await fetchUserInformation();
        menuItems.value;
    });
}
// ===============================================================================

// 定义刷新页面的方法
export const refreshPage = () => {
    // 刷新页面
    window.location.reload();
};

// ======================================== 要提交的数据 ===================================================

export const editForm = reactive({
    username: "",
    email: "",
    sex: '0',
    user_id:"",
    telephone: "",
    old_telephone: "",
    code:""
})

const defaultEditForm = {
    username: "",
    email: "",
    sex: 0,
    user_id: "",
    telephone: "",
    old_telephone: "",
    code:""
};

// =========================================== 获取的用户数据 ==================================================
// 使用 computed 创建一个响应式的计算属性
export const sex = computed(() => {
    const sex_index = userData.gender;
    switch (sex_index) {
        case '0':
            return '保密';
        case '1':
            return '男';
        case '2':
            return '女';
        default:
            return '';
    }
});


// 修改数据
export const isShow = reactive({
    usernameShow: false,
    sexShow: false,
    telephoneShow: false,
    emailShow: false,
})


export const menuItems = computed(() => {
    return [
        { label: '昵称', data: userData.username, isEdit: true, isShow: "usernameShow",
            title: '♡ 编辑昵称', description: 'Tips：以字母开头，仅支持数字和字母，字数5-20'},

        { label: '性别', data: sex, isEdit: true, isShow: "sexShow",
            title: '♡ 选择您的性别', description: 'Tips：我们保证您的信息安全，这只是为了让我们更好地了解我们的用户群体'},

        { label: '手机', data: userData.telephone, isEdit: true, isShow: "telephoneShow",
            title: '♡ 修改绑定的手机号', description: "Tips：修改需要发送验证码到新手机号并验证之前绑定的手机号"},

        { label: '邮箱', data: userData.email, isEdit: true, isShow: "emailShow",
            title: '♡ 修改绑定的邮箱', description: 'Tips：我们重视您的隐私，将保护您的邮箱信息'},

        { label: 'UID', data: userStore.UID, isEdit: false},
    ];
});


// ========================================== 修改用户数据 =====================================================
export function editUserInfo (info: string) {
    // 验证数据的正则表达式
    const usernameReg = /^[A-Za-z][A-Za-z0-9]{4,19}$/;

    // UID
    editForm.user_id = userStore.UID;

    // URL
    let url = ''

    if (info == '昵称') {
        if (!usernameReg.test(editForm.username)) {
            return ElMessage.warning('格式有误：以字母开头，仅支持数字和字母，字数5-20')
        } else {
            console.log(JSON.stringify(editForm))
            url = "/api/user/homepage/edit_username/"
            submitForm(url, 'username').then()
        }
    } else if (info == '性别') {
        url = "/api/user/homepage/edit_gender/"
        submitForm(url, 'gender').then()
    } else if (info == '手机') {
        url = "/api/user/homepage/edit_telephone/"
        submitForm(url, 'telephone').then()
    } else if (info == '邮箱') {
        url = "/api/user/homepage/edit_email/"
        console.log(editForm)
        submitForm(url, 'email').then()
    }
}

async function submitForm (url: string, key: string) {
    try {
        const res = await axios_request(url, JSON.stringify(editForm), 'post')
        console.log("POST请求返回的数据：" + res)
        console.log(res)
        if (res.status == 200) {
            ElNotification({
                title: 'Success',
                message: h('span', {style: {color: '#65e0c2', fontSize: '16px', fontWeight: '900'}}, res.data.msg),
                type: 'success',
                offset: 65,
                showClose: false,
                customClass: 'custom-notification'
            })

            const keys = [key];
            const newUserData = await userStore.fetchUserInfo(keys, userStore.UID);
            userStore.updateUserData(newUserData);

            // 重置提交表中的数据
            Object.assign(editForm, defaultEditForm);
            console.log(editForm)

            await sleep(1000)
            refreshPage()

        } else if (res.status == 202) {
            ElNotification({
                title: 'Error',
                message: h('span', {style: {color: '#65e0c2', fontSize: '16px', fontWeight: '900'}}, res.data.msg),
                type: 'error',
                offset: 65,
                showClose: false,
                customClass: `custom-notification`
            })
        }
    } catch (error) {
        console.log(error)
    }
}

